package com.example.doctor.utils;

import com.example.common.support.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * http请求工具
 *
 * @Author wxy
 * @Date 2020/10/10 13:03
 * @Version 1.0
 */
@Slf4j
@Component
public class HttpUtils {

    @Resource
    private RestTemplate restTemplate;

    public void check(Object obj) {
        if (ObjectUtils.isEmpty(obj)) {
       throw new ApiException(10000, "对象不能为空");
        }
    }

    /**
     * @param url      url地址
     * @param inputMap 入参Map（key为字段名，value为值）
     * @return 带参数的GET请求
     */
    public Map<String,Object> get(String url, Map<String, String> inputMap) {
        check(url);
        check(inputMap);
        StringBuilder data = new StringBuilder();
        for (Map.Entry<String, String> entry : inputMap.entrySet()) {
            data.append(entry.getKey()).append("={").append(entry.getKey()).append("}&");
        }
        String intercept = data.toString().substring(0, data.length() - 1);
        url = url + "?" + intercept;

        ResponseEntity<Map> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                new HttpEntity<String>(""),
                Map.class,
                inputMap);
        System.out.println(response);
        Map<?, ?> map = response.getBody();
       return (Map<String, Object>) map;
    }

}
